package net.amsoft.iservice.management.webapp.struts.action;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.amsoft.iservice.management.util.FileUploadUtil;
import net.amsoft.iservice.management.util.IBrokerConstants;
import net.amsoft.iservice.management.util.IBrokerUtil;
import net.amsoft.iservice.management.webapp.struts.form.SaveImageForm;
import net.amsoft.iservice.util.IServiceConstants;
import net.amsoft.iservice.util.IServiceUtil;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * Gets called when user wants to save or cancel the modified image files for 
 * logo, ad-banner or related-mews. <br>
 * 
 * If user has opted to cancel, the new file is deleted from the temporary 
 * folder and the old image is visible <br>
 * 
 * If user has opted to save the changes, old image is replaced by the new 
 * image and deleted from the temporary folder <br>
 * 
 * @author mukta
 */
public class SaveImageAction extends Action 
{
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception 
	{
		SaveImageForm myForm = (SaveImageForm) form;
		String serviceName = (String) request.getSession().getAttribute("Service");
		
		// Check if user has come through proper channel or simply typed URL in browser
        if (serviceName==null)
	    {
            IServiceUtil.log(IServiceConstants.DEBUG, this, "execute(): redirect to=" + 
            		IBrokerConstants.FWD_LOGIN);
	        return mapping.findForward(IBrokerConstants.FWD_LOGIN);
	    }       

		// Get source file to copy
		String imagePath = "";
		String logofile =  "";
		String source = "";

		// Check if stylesheet is being updated
		if ("stylesheet".equals(myForm.getImageType()))
		{
			// Specify source and destination stylesheet
		    imagePath = "styleSheets/iservices.css";
			logofile =  (String) request.getSession().getAttribute("ServerName") + "_iservices.css";
		    source = (String) request.getSession().getAttribute("ServerPath") + "staging/" + logofile;
		}
		else
		{
			// Specify source and destination image file
			imagePath = "images/" + (String) request.getSession().getAttribute("ServerName") + "/" + myForm.getImageType() + ".gif";
			logofile =  (String) request.getSession().getAttribute("ServerName") + "_" + myForm.getImageType() + ".gif";
			source = (String) request.getSession().getAttribute("ServerPath") + "staging/" + logofile;
		}
		
		if ((isCancelled(request)) || ("cancel".equals(myForm.getAction())))
		{
            IServiceUtil.log(IServiceConstants.DEBUG, this, 
                    "execute(): Clicked Cancel to save " + myForm.getImageType() + " file..");
            IServiceUtil.log(IServiceConstants.INFO, this, 
                    "execute(): Calling FileUploadUtil.deleteFile()");
			FileUploadUtil.deleteFile(source);
			
            IServiceUtil.log(IServiceConstants.DEBUG, this, 
                    "execute(): redirect to=" + IBrokerConstants.FWD_CANCEL);
			return mapping.findForward(IBrokerConstants.FWD_CANCEL);
		}
		
		// Save file at all the locations
        ActionMessages oMsgs = new ActionErrors();
		try {
			IServiceUtil.log(IServiceConstants.INFO, this, 
					"execute(): Calling FileUploadUtil.saveFile()");
            FileUploadUtil.saveFile(source, imagePath, serviceName);
        } catch (FileNotFoundException e) {
            IServiceUtil.log(IServiceConstants.ERROR, this, 
                    "execute(): Exception=" + e.getMessage());
            oMsgs.add(ActionMessages.GLOBAL_MESSAGE, 
                    new ActionMessage(IBrokerConstants.ERR_FILE_NOT_FOUND));
            saveErrors(request.getSession(), oMsgs);
            IServiceUtil.log(IServiceConstants.DEBUG, this, 
                    "execute(): redirect to="+ mapping.getInputForward());
            return mapping.getInputForward();
        } catch (IOException e) {
            IServiceUtil.log(IServiceConstants.ERROR, this, 
                    "execute(): Exception=" + e.getMessage());
            oMsgs.add(ActionMessages.GLOBAL_MESSAGE, 
                    new ActionMessage(IBrokerConstants.ERR_IO_FAILED));
            saveErrors(request.getSession(), oMsgs);
            IServiceUtil.log(IServiceConstants.DEBUG, this, 
                    "execute(): redirect to="+ mapping.getInputForward());
            return mapping.getInputForward();
        }
		
		// Check if banner image is uploaded, update session attribute and Database
		if ("ad-banner".equals(myForm.getImageType()))
		{
            IServiceUtil.log(IServiceConstants.DEBUG, this, "execute(): " +
                    "Additional functionality to save ad banner image");
		    
			// Get server name and banner
		    String serverName = (String) request.getSession().getAttribute("ServerName");
		    String banner = "images/" + serverName + "/ad-banner.gif";
		    
			// Update session attribute value
            IServiceUtil.log(IServiceConstants.DEBUG, this, 
                    "execute(): Setting session attribute Banner=" + banner);
			request.getSession().setAttribute("Banner", banner);

			// Update DB
            IServiceUtil.log(IServiceConstants.DEBUG, this, 
                    "execute(): Calling \"IBrokerUtil.processAdBanner()\" to update database");
			IBrokerUtil.processAdBanner(serverName, banner, (String) request.getSession().getAttribute("Service"));
		}

        IServiceUtil.log(IServiceConstants.DEBUG, this, 
                "execute(): redirect to="+ IBrokerConstants.FWD_SUCCESS);
		return mapping.findForward(IBrokerConstants.FWD_SUCCESS);
	}

}